<template>
  <div>
    <transition-group name="drag" class="list" tag="ul">
      <li @dragstart="dragstart(index)" @dragenter="dragenter($event, index)" @dragover.prevent draggable
        v-for="(item, index) in list" :key="item.label" class="list-item">
        {{ item.label }}
      </li>
    </transition-group>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        { label: "列表1" },
        { label: "列表2" },
        { label: "列表3" },
        { label: "列表4" },
        { label: "列表5" },
        { label: "列表6" },
      ],
      dragIndex: "",
    };
  },
  created() {

    //随机生成字母
    let str = "";
    for (let i = 0; i < 8; i++) {
      str += String.fromCharCode(
        Math.floor(Math.random() * 26) + "A".charCodeAt(0)//大写字母"A".charCodeAt(0)，小写字母"a".charCodeAt(0)
      )
    }
    console.log("str: ", str)
    console.log("str: ", this.getRanNum())
    console.log("str: ", this.formatTime())
    this.varTest()

  },
  methods: {
    varTest() {
      if (true) {
        var aa = "测试var";
      }
      console.log(aa);                    //由于var是	Function级别的，所以这里可以取到值
    },
    letTest() {
      // if (true) {
      //   let bb = "测试let";
      //   const cc = "测试const";
      // }
      // console.log(bb);//报错,由于let是Block级别的，所以这里取不到值
      // console.log(cc);//报错,由于let是Block级别的，所以这里取不到值
    },
    formatTime() {
      const time = new Date()
      var h = String(time.getHours());
      var m = String(time.getMinutes());
      var s = String(time.getSeconds());
      h = h.length < 2 ? '0' + h : h;
      m = m.length < 2 ? '0' + m : m;
      s = s.length < 2 ? '0' + s : s;
      return h + m + s
    },
    getRanNum() {
      var result = [];
      for (var i = 0; i < 4; i++) {
        var ranNum = Math.ceil(Math.random() * 25); //生成一个0到25的数字
        //大写字母'A'的ASCII是65,A~Z的ASCII码就是65 + 0~25;然后调用String.fromCharCode()传入ASCII值返回相应的字符并push进数组里
        result.push(String.fromCharCode(65 + ranNum));
      }
      return result.join('');
    },
    dragstart(index) {
      this.dragIndex = index;
    },
    dragenter(e, index) {
      // 避免源对象触发自身的dragenter事件
      if (this.dragIndex !== index) {
        const moving = this.list[this.dragIndex];
        this.list.splice(this.dragIndex, 1);
        this.list.splice(index, 0, moving);
        // 排序变化后目标对象的索引变成源对象的索引
        this.dragIndex = index;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.list {
  list-style: none;
  .drag-move {
    transition: transform 0.3s;
  }
  .list-item {
    cursor: move;
    width: 300px;
    background: #ea6e59;
    border-radius: 4px;
    color: #fff;
    margin-bottom: 6px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
}
</style>
